package data

import (
	"customer/internal/biz"
	"customer/internal/conf"
	"fmt"
	"github.com/redis/go-redis/v9"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"

	"github.com/go-kratos/kratos/v2/log"
	"github.com/google/wire"
)

// ProviderSet is data providers.
var ProviderSet = wire.NewSet(NewData, NewGreeterRepo, NewCustomerData)

// Data .
type Data struct {
	Rdb *redis.Client
	DB  *gorm.DB
	// TODO wrapped database client
}

// NewData .
func NewData(c *conf.Data, logger log.Logger) (*Data, func(), error) {
	//初始化rdb
	//redis:临时存储
	data := &Data{}
	//options, err := redis.ParseURL("redis://localhost:6379/2?dial_timeout=1")
	redisURL := fmt.Sprintf("redis://%s/2?dial_timeout=%d", c.Redis.Addr, 1)
	options, err := redis.ParseURL(redisURL)
	if err != nil {
		data.Rdb = nil
	}
	//new client 不会立即建立客户端，需要执行命令是才会连接
	data.Rdb = redis.NewClient(options)

	//初始化mysqldb
	dsn := c.Database.Source
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		data.DB = nil
	}
	data.DB = db
	migrateTable(data.DB)
	cleanup := func() {
		_ = data.Rdb.Close()
		log.NewHelper(logger).Info("closing the data resources")
	}
	return data, cleanup, nil
}
func migrateTable(db *gorm.DB) {
	if err := db.AutoMigrate(&biz.Customer{}); err != nil {
		log.Infof("AutoMigrate table err %s", err)
	}
}
